package de.tto.dating.servlet;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.googlecode.objectify.Key;

import de.tto.dating.entities.Image;
import de.tto.dating.entities.ImageDAO;
import de.tto.dating.entities.User;

public class Upload extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5394336628194564932L;

	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
		BlobKey blobKey = blobs.get("upload_foto");

		if (blobKey == null) {
			res.sendRedirect("/");
			return;
		}

//		com.google.appengine.api.images.Image uploadImage = ImagesServiceFactory
//				.makeImageFromBlob(blobKey);

		InputStream content = getServletContext().getResourceAsStream(
				"/img/logo.jpg");
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bos.write(content.read());
		byte[] ba = bos.toByteArray();

		try {
			String uplodUrl = blobstoreService.createUploadUrl("/scale");
			URL url = new URL("http://localhost:8888" + uplodUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();

			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "keep-alive");
			connection
					.setRequestProperty("Content-Type", "multipart/form-data");
			connection.setRequestProperty("Content-Length", ba.length + "");

			DataOutputStream d = new DataOutputStream(
					connection.getOutputStream());
			d.write(ba);

			// OutputStreamWriter writer = new OutputStreamWriter(
			// connection.getOutputStream());

			int code = connection.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				System.out.println("OK " + code);
			} else {
				System.out.println("ERROR " + code);
			}
		} catch (MalformedURLException e) {
			System.out.println(e.getMessage());
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("currentUser");
		if (user == null) {
			blobstoreService.delete(blobKey);
			res.sendRedirect("/login.jsp");
			return;
		}

		Image img = new Image();
		img.setOriginal(blobKey.getKeyString());

		img.setUser(new Key<User>(User.class, user.getOid()));

		// img.setUser(user);
		// user.getImages().add(img);
		ImageDAO imageDAO = new ImageDAO();
		Image savedImage = imageDAO.save(img);
		if (savedImage == null) {
			res.sendRedirect("/");
			return;
		}

		res.sendRedirect("/home.jsp");

	}

}
